package cn.yh.register.hosp.service.impl;

import cn.yh.register.hosp.repository.DepartmentRepository;
import cn.yh.register.hosp.repository.HospitalRepository;
import cn.yh.register.hosp.service.DepartmentService;
import cn.yh.register.model.hosp.Department;
import cn.yh.register.vo.hosp.DepartmentVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

   @Autowired
    HospitalRepository hospitalRepository;

   @Autowired
    DepartmentRepository departmentRepository;

    /**
     * 上传科室接口
     * @param objectMap 参数信息
     */
    @Override
    public void saveDepartment(Map<String, Object> objectMap) {
        //转成对象的形式保存
        Department department = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Department.class);
        //根据医院hoscode和科室编号判断是否存在  这个是查的我们的老数据
        Department depart = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (depart == null){
            //不存在，则插入  需要插入一些额外字段
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
        }else{
            //存在 更新
            department.setCreateTime(depart.getCreateTime());
            department.setId(depart.getId());
            department.setIsDeleted(depart.getIsDeleted());
        }
        department.setUpdateTime(new Date());
        departmentRepository.save(department);
    }

    /**
     * 分页查询科室列表
     *
     * @param hoscode 医院编号
     * @param page    页码
     * @param limit   每页条数
     * @return 科室列表分页数据
     */
    @Override
    public Page<Department> getPageList(String hoscode, Integer page, Integer limit) {
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        //分页
        PageRequest pageRequest = PageRequest.of(page - 1, limit, Sort.by(Sort.Direction.DESC, "createTime"));
        return departmentRepository.findAll(example, pageRequest);
    }

    /**
     * 删除医院科室列表
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     */
    @Override
    public void remove(String hoscode, String depcode) {
        //先查
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //再删
        if (department != null){
            departmentRepository.delete(department);
        }
    }

    /**
     * 根据医院编号查询对应的医院科室
     * @param hoscode 医院编号
     * @return 科室信息
     */
    @Override
    public List<DepartmentVo> findDepartmentTree(String hoscode) {
        //先根据医院编号查医院所有科室信息
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        //查询得到的list集合
        List<Department> departmentList = departmentRepository.findAll(example);
        /**
         * 转成map 根据大科室编号分组（BigCode）
         * 分组转成map  key：大科室编号  value：大科室对应的小科室列表集合
         * 大科室编号相同的小科室的分成一组
         */
        Map<String, List<Department>> departmentMap = departmentList.stream()
                .collect(Collectors.groupingBy(Department::getBigcode));
        //装大科室的list
        List<DepartmentVo> voList = new ArrayList<>();
        /**
         * 组装外面的大科室，然后把小科室也组装好给到大科室的children属性中
          遍历集合  组装数据  拿到一个个entry对象  里面封装的是key  和 value
         大科室组装成 DepartmentVo对象中 小科室也组装成vo对象，然后塞进去
         */
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //取里面的key 也就是大科室编号
            String bigCode = entry.getKey();
            //取里面的value  也就是小科室列表
            List<Department> smallList = entry.getValue();
            //获取大科室名称 小科室列表集合中有bigCode、bigName属性，整个列表数据的大科室名称都是同一个大科室名称
            String bigName = smallList.get(0).getBigname();
            //组装小科室的list集合
            List<DepartmentVo> smallVoList = new ArrayList<>();
            // 组装小科室 小科室里面也有科室编号  科室名称 组装成DepartmentVo对象
            for (Department small :smallList) {
                DepartmentVo smallVo = new DepartmentVo();
                smallVo.setDepcode(small.getDepcode());
                smallVo.setDepname(small.getDepname());
                //装到一个list集合  一个小科室对象放到一个list集合当中去
                smallVoList.add(smallVo);
            }
            //组装大科室  也是一个VO对象
            DepartmentVo bigVo = new DepartmentVo();
            bigVo.setDepcode(bigCode);
            bigVo.setDepname(bigName);
            //把小科室装进去
            bigVo.setChildren(smallVoList);
            //装入list
            voList.add(bigVo);
        }
        return voList;
    }

    /**
     * 获取科室信息
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return 科室信息
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
    }
}
